package cn.turboinfo.fuyang.api.domain.admin.usecase.account;

import cn.turboinfo.fuyang.api.domain.common.service.account.CompanyAccountService;
import cn.turboinfo.fuyang.api.domain.common.service.wechat.WechatPayService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.account.CompanyAccount;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

@Slf4j
@RequiredArgsConstructor
@Component
public class CompanyAccountDeleteUseCase extends AbstractUseCase<CompanyAccountDeleteUseCase.InputData, CompanyAccountDeleteUseCase.OutputData> {
    private final CompanyAccountService companyAccountService;

    private final WechatPayService wechatPayService;

    @Override
    protected OutputData doAction(InputData inputData) {
        Long id = inputData.getId();
        Long companyId = inputData.getCompanyId();

        CompanyAccount companyAccount = companyAccountService.getByIdEnsure(id);

        if (!companyId.equals(companyAccount.getCompanyId())) {
            throw new IllegalArgumentException("无权删除该账户");
        }

        try {
            wechatPayService.deleteProfitSharingReceiver(companyAccount.getAccount(), companyAccount.getType().getCode());
            companyAccountService.deleteById(id);

        } catch (RuntimeException e) {
            log.error("删除分账账户失败", e);
            throw e;
        }

        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "编码不能为空"
        )
        @Positive
        private Long id;

        @NotNull(
                message = "企业ID不能为空"
        )
        @Positive
        private Long companyId;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
    }
}
